package com.wfl.sampling.sockets;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * WebSocket服务器，用于处理用户的实时通信。
 */
@ServerEndpoint(value = "/websocket/{userId}")
@Component
public class WebSocketServer {

    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);
    private static final ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    private static int onlineCount = 0;
    private Session session;
    private String userId = "";

    /**
     * 用户连接WebSocket时调用。
     *
     * @param session 用户的WebSocket会话
     * @param userId 用户的唯一标识
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
        }
        webSocketMap.put(userId, this);
        addOnlineCount();
        log.info("User connected: " + userId + ", Current online users: " + getOnlineCount());

        try {
            sendMessage("Connection successful");
        } catch (IOException e) {
            log.error("User: " + userId + ", Network error: " + e.getMessage());
        }
    }

    /**
     * 用户断开WebSocket连接时调用。
     */
    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            subOnlineCount();
        }
        log.info("User disconnected: " + userId + ", Current online users: " + getOnlineCount());
    }

    /**
     * 收到用户消息时调用。
     *
     * @param message 用户发送的消息
     * @param session 用户的WebSocket会话
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("Message from user: " + userId + ": " + message);
        if (StringUtils.isNotBlank(message)) {
            try {
                handleChatMessage(message, this.userId);
            } catch (JSONException e) {
                log.error("JSON parsing error: " + e.getMessage());
            }
        }
    }

    /**
     * WebSocket连接出错时调用。
     *
     * @param session 用户的WebSocket会话
     * @param error 异常对象
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("Error in connection for user: " + this.userId + ", Reason: " + error.getMessage());
    }

    /**
     * 向用户发送消息。
     *
     * @param message 要发送的消息
     * @throws IOException 如果发送消息时发生IO异常
     */
    public void sendMessage(String message) throws IOException {
        this.session.getAsyncRemote().sendText(message);
    }

    public void sendOneMessage(String message, String userId) throws IOException {
        log.info("Sending message to user: " + userId + ": " + message);
        if (StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId)) {
            webSocketMap.get(userId).sendMessage(message);
        } else {
            log.error("User: " + userId + ", not online");
        }
    }

    public void sendMoreMessage(String message, String[] userIds) throws IOException {
        log.info("Sending message to multiple users: " + message);
        for (String id : userIds) {
            if (webSocketMap.containsKey(id)) {
                webSocketMap.get(id).sendMessage(message);
            } else {
                log.error("User: " + id + ", not online");
            }
        }
    }

    public void sendAllMessage(String message) throws IOException {
        log.info("Broadcasting message: " + message);
        for (Map.Entry<String, WebSocketServer> entry : webSocketMap.entrySet()) {
            entry.getValue().sendMessage(message);
        }
    }

    /**
     * 处理聊天消息。
     *
     * @param message 接收到的聊天消息
     * @param senderId 发送者ID
     * @throws JSONException 如果解析JSON时发生错误
     */
    private void handleChatMessage(String message, String senderId) throws JSONException {
        JSONObject jsonMessage = new JSONObject(message);
        String receiverId = jsonMessage.getString("receiverId");
        String msgText = jsonMessage.getString("text");
        if (webSocketMap.containsKey(receiverId)) {
            try {
                webSocketMap.get(receiverId).sendMessage(createJsonMessage(msgText, senderId, receiverId));
            } catch (IOException e) {
                log.error("Error sending message from user: " + senderId + " to user: " + receiverId, e);
            }
        } else {
            log.error("Receiver: " + receiverId + " is not connected.");
        }
    }

    /**
     * 创建JSON格式的消息。
     *
     * @param text 消息文本
     * @param senderId 发送者ID
     * @param receiverId 接收者ID
     * @return 格式化的JSON字符串
     * @throws JSONException 如果构建JSON时发生错误
     */
    private String createJsonMessage(String text, String senderId, String receiverId) throws JSONException {
        JSONObject jsonMessage = new JSONObject();
        jsonMessage.put("type", "chat");
        jsonMessage.put("text", text);
        jsonMessage.put("senderId", senderId);
        jsonMessage.put("receiverId", receiverId);
        return jsonMessage.toString();
    }

    public synchronized int getOnlineCount() {
        return onlineCount;
    }

    public synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}
